package com.examsystem.filter;

import com.examsystem.util.JwtUtil;
import com.examsystem.pojo.PaperClass;
import com.examsystem.service.PaperClassService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
/**
 * @author fire'ge
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {

    @Resource
    private PaperClassService paperClassService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取到该拦截路径的token和paperId
        String token = request.getHeader("token");
        int jwtUserId = JwtUtil.getJWTUserId(token);
        int paperId = Integer.parseInt(request.getParameter("paperId"));
        //根据获取的信息来查询该试卷的考试时间范围
        PaperClass paperClass = paperClassService.queryPaperClassByUserIdAndPaperId(paperId, jwtUserId);
        Timestamp endExam = new Timestamp(paperClass.getPcTime().getTime() + paperClass.getPcExamTime() * 60L);
        boolean flag = System.currentTimeMillis()>=paperClass.getPcTime().getTime()&&
                System.currentTimeMillis()<= endExam.getTime();
        //判断世时间范围
        if (flag){
            request.getSession().setAttribute("examStart",paperClass.getPcTime());
            request.getSession().setAttribute("examEnd",endExam);
            return true;
        }
        //不通过则抛出异常
        else {
            throw new RuntimeException("不在指定考试时间的范围内");
        }
    }
}
